package com.cn.auth.config;

import com.cn.auth.vo.UserDetailsWrap;
import com.cn.auth.redis.RedisConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zhoujunming
 * @Description JWT内容增强器
 * @date 2022/6/8 15:04
 * @email zhoujunming@bluemoon.com.cn
 */
@Configuration
public class JwtTokenEnhancerConfig implements TokenEnhancer {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        //如果是客户端模式，则不使用token增强
        if (oAuth2Authentication.isClientOnly()){
            return oAuth2AccessToken;
        }
        UserDetailsWrap user = (UserDetailsWrap) oAuth2Authentication.getPrincipal();
        Map<String, Object> info = new HashMap<>();
        //把用户ID设置到JWT中
        info.put("user_id", user.getUser().getId());

        //将用户信息放入reids缓存
        //清除密码
        user.getUser().setPassword("");
        redisTemplate.opsForValue().set(RedisConstant.USER_INFO.getKey(user.getUser().getId().toString()),user.getUser(),7L, TimeUnit.DAYS);

        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }


}
